import { login } from '../../api/auth';

Page({
  data: {
    loading: false
  },

  onLoad() {
    // 检查是否已登录
    const token = wx.getStorageSync('token');
    if (token) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  // 获取用户信息
  async getUserProfile() {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      // 获取用户信息
      const userProfile = await wx.getUserProfile({
        desc: '用于完善用户资料'
      });

      // 获取登录code
      const { code } = await wx.login();
      
      // 调用登录接口
      const result = await login({
        code,
        userInfo: {
          nickName: userProfile.userInfo.nickName,
          avatarUrl: userProfile.userInfo.avatarUrl
        }
      });

      // 保存登录信息
      wx.setStorageSync('token', result.accessToken);
      wx.setStorageSync('userInfo', result.userInfo);

      // 跳转到首页
      wx.switchTab({
        url: '/pages/index/index'
      });

      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: '登录失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  }
}); 